package com.framework.service.module.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.framework.common.model.response.R;
import com.framework.common.util.encrypt.MD5Util;
import com.framework.common.util.other.GenerateMantissaUtil;
import com.framework.common.util.other.NumeralUtil;
import com.framework.common.util.other.UUIDUtil;
import com.framework.common.util.randomCode.RandomCodeUtil;
import com.framework.common.util.redis.RedisKeyUtil;
import com.framework.common.util.redis.RedisPrefixUtil;
import com.framework.mapper.module.user.RightsMapper;
import com.framework.mapper.module.user.StratumMapper;
import com.framework.mapper.module.user.UserMapper;
import com.framework.model.module.user.Rights;
import com.framework.model.module.user.Stratum;
import com.framework.model.module.user.vo.UserVo;
import com.framework.model.system.vo.SystemUserVo;
import com.framework.service.base.BaseService;
import com.framework.service.module.user.UserService;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author 龘鵺
 * @version 1.0
 * @className com.framework.service.module.user.impl.UserServiceImpl
 * @description 用户业务接口实现类
 * @datetime 2024-06-20 20:28:00
 */
@Service("userServiceImpl")
public class UserServiceImpl extends BaseService implements UserService {
    private Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StratumMapper stratumMapper;
    @Autowired
    private RightsMapper rightsMapper;

    /**
     * @param id 1 编号
     * @return com.framework.model.module.user.vo.UserVo
     * @title 根据编号查询用户
     * @description 根据编号查询用户
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    public UserVo getByIdParam(Long id) {
        UserVo row = new UserVo();
        SystemUserVo systemUserVo = getUser();
        row.setId(id);
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        UserVo p = userMapper.selectByParamSalt(row);
        if (p == null) {
            return new UserVo();
        }
        return p;
    }

    /**
     * @param row 1 用户类
     * @return com.framework.common.model.response.R
     * @title 新增用户
     * @description 新增用户
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> save(UserVo row) {
        SystemUserVo systemUserVo = getUser();
        UserVo param = new UserVo();
        param.setPhone(row.getPhone());
        int isExistPhone = userMapper.isExistTwo(param);
        if (isExistPhone > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("手机号重复,请勿重复创建!");
        }
        param.setPhone(null);
        param.setMail(row.getMail());
        int isExistMail = userMapper.isExistTwo(param);
        if (isExistMail > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("邮箱重复，请重新添加！");
        }
        param.setMail(null);
        String account = String.valueOf(GenerateMantissaUtil.GenerateNum(NumeralUtil.POSITIVE_TEN_MILLION));
        param.setAccount(account);
        int isExistAccount = userMapper.isExistTwo(param);
        if (isExistAccount > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("账号重复，请重新添加！");
        }
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setCreateId(userId);
        row.setCreateTime(date);
        row.setOperaterId(userId);
        row.setOperaterTime(date);
        row.setOperaterStatus(NumeralUtil.POSITIVE_ONE);
        row.setChannelStatus(NumeralUtil.POSITIVE_NINE_THOUSAND_NINE_HUNDRED_AND_NINETY_NINE);
        row.setStaffStatus(NumeralUtil.POSITIVE_SEVEN_THOUSAND_SEVEN_HUNDRED_AND_SEVENTY_SEVEN);
        String password = RandomCodeUtil.getStringRandomCodeToValue(NumeralUtil.POSITIVE_EIGHT);
        String salt = UUIDUtil.getUUID();
        String pwd = MD5Util.MD5EncodeToPassword(password, salt);
        row.setPassword(pwd);
        row.setAccount(account);
        row.setSalt(salt);
        userMapper.insertSelective(row);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", account);
        jsonObject.put("password", password);
        if (row == null && (row.getId() == null || row.getId().longValue() < NumeralUtil.POSITIVE_ONE)) {
            return R.fail("创建帐号失败，请重试!");
        }
        Stratum stratum = new Stratum();
        stratum.setId(row.getId());
        stratum.setCreateId(userId);
        stratum.setCreateTime(date);
        stratum.setOperaterId(userId);
        stratum.setOperaterTime(date);
        stratum.setOperaterStatus(NumeralUtil.POSITIVE_ONE);

        Rights rights = new Rights();
        rights.setId(row.getId());
        rights.setCreateId(userId);
        rights.setCreateTime(date);
        rights.setOperaterId(userId);
        rights.setOperaterTime(date);
        rights.setOperaterStatus(NumeralUtil.POSITIVE_ONE);
        rights.setEnableStatus(NumeralUtil.POSITIVE_ONE);
        rights.setInvitationStatus(NumeralUtil.POSITIVE_SEVEN_THOUSAND_SEVEN_HUNDRED_AND_SEVENTY_SEVEN);
        rights.setRebateRatioStatus(NumeralUtil.POSITIVE_SEVEN_THOUSAND_SEVEN_HUNDRED_AND_SEVENTY_SEVEN);
        rightsMapper.insertSelective(rights);
        stratumMapper.insertSelective(stratum);
        return R.ok(jsonObject);
    }

    /**
     * @param row 1 用户类
     * @return com.framework.common.model.response.R
     * @title 编辑用户
     * @description 编辑用户
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> edit(UserVo row) {
        SystemUserVo systemUserVo = getUser();
        UserVo queryParam = new UserVo();
        queryParam.setId(row.getId());
        queryParam = userMapper.selectByParam(queryParam);
        if (queryParam == null) {
            return R.fail("编辑信息不存在!");
        }
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setSalt(null);
        row.setOperaterTime(date);
        row.setOperaterId(userId);
        row.setOperaterStatus(NumeralUtil.POSITIVE_TWO);
        userMapper.updateByPrimaryKeySelective(row);
        return R.ok();
    }

    /**
     * @param id 1 编号
     * @return com.framework.common.model.response.R
     * @title 重置密码
     * @description 重置密码
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     */
    @Override
    public R<?> resetPassword(Long id) {
        String timeKey = RedisKeyUtil.getObjKey(RedisPrefixUtil.PREFIX_STR_USER_RESET_PASSWORD_KEY, RedisPrefixUtil.PREFIX_STR_USER_RESET_PASSWORD_KEY,
                id.toString());
        long expireNum = redisUtil.getExpire(timeKey);
        if (expireNum > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("操作频繁,请" + expireNum + "秒后重试!");
        }
        UserVo queryParam = new UserVo();
        SystemUserVo systemUserVo = getUser();
        queryParam.setId(id);
        queryParam = userMapper.selectByParam(queryParam);
        if (queryParam == null) {
            return R.fail("信息不存在!");
        }
        redisUtil.setString(timeKey, NumeralUtil.STRING_POSITIVE_ZERO, NumeralUtil.POSITIVE_THIRTY);
        String password = RandomCodeUtil.getStringRandomCodeToValue(NumeralUtil.POSITIVE_EIGHT);
        String pwd = MD5Util.MD5EncodeToPassword(password, queryParam.getSalt());
        Long userId = systemUserVo.getId();
        Date date = new Date();
        UserVo row = new UserVo();
        row.setOperaterId(userId);
        row.setOperaterTime(date);
        row.setOperaterStatus(NumeralUtil.POSITIVE_ONE);
        row.setPassword(pwd);
        row.setId(queryParam.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("account", queryParam.getAccount());
        jsonObject.put("password", password);
        return R.ok(jsonObject);
    }

    /**
     * @param id 1 编号
     * @return com.framework.common.model.response.R
     * @title 启用禁用方法
     * @description 启用禁用方法
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     */
    @Override
    public R<?> enable(Long id) {
        String timeKey = RedisKeyUtil.getObjKey(RedisPrefixUtil.PREFIX_STR_USER_ENABLE_KEY, RedisPrefixUtil.PREFIX_STR_USER_ENABLE_KEY,
                id.toString());
        long expireNum = redisUtil.getExpire(timeKey);
        if (expireNum > NumeralUtil.POSITIVE_ZERO) {
            return R.fail("操作频繁,请" + expireNum + "秒后重试!");
        }
        UserVo queryParam = new UserVo();
        SystemUserVo systemUserVo = getUser();
        queryParam.setId(id);
        queryParam = userMapper.selectByParam(queryParam);
        if (queryParam == null) {
            return R.fail("信息不存在!");
        }
        redisUtil.setString(timeKey, NumeralUtil.STRING_POSITIVE_ZERO, NumeralUtil.POSITIVE_FIFTEEN);
        Long userId = systemUserVo.getId();
        Date date = new Date();
        UserVo row = new UserVo();
        row.setOperaterId(userId);
        row.setOperaterTime(date);
        row.setOperaterStatus(NumeralUtil.POSITIVE_ONE);
        row.setId(queryParam.getId());
        if (queryParam.getEnableStatus().intValue() == NumeralUtil.POSITIVE_ONE) {
            //需要踢出登录，禁用后，后续完善
            row.setEnableStatus(NumeralUtil.POSITIVE_TWO);
        } else {
            row.setEnableStatus(NumeralUtil.POSITIVE_ONE);
        }
        userMapper.updateByPrimaryKeySelective(row);
        return R.ok();
    }

    /**
     * @param id 1 编号
     * @return com.framework.common.model.response.R
     * @title 删除用户
     * @description 删除用户
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> delete(Long id) {
        UserVo row = new UserVo();
        SystemUserVo systemUserVo = getUser();
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setId(id);
        row.setOperaterTime(date);
        row.setOperaterId(userId);
        row.setOperaterStatus(NumeralUtil.NEGATIVE_ONE);
        userMapper.delete(row);
        return R.ok();
    }

    /**
     * @param idList 1 编号集合
     * @return com.framework.common.model.response.R
     * @title 批量删除用户
     * @description 批量删除用户
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    @Transactional
    public R<?> batchDeleteList(List<Long> idList) {
        UserVo row = new UserVo();
        SystemUserVo systemUserVo = getUser();
        Long userId = systemUserVo.getId();
        Date date = new Date();
        row.setIdList(idList);
        row.setOperaterTime(date);
        row.setOperaterId(userId);
        row.setOperaterStatus(NumeralUtil.NEGATIVE_ONE);
        //userMapper.deleteList(row);
        return R.ok();
    }

    /**
     * @param row 1 用户类
     * @return java.util.List<com.framework.model.module.user.vo.UserVo>
     * @title 查询用户集合
     * @description 查询用户集合
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    public List<UserVo> findByList(UserVo row) {
        SystemUserVo systemUserVo = getUser();
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        List<UserVo> list = userMapper.findByList(row);
        return list;
    }

    /**
     * @param row 1 用户类
     * @return com.framework.common.model.response.R
     * @title 分页查询用户列表
     * @description 分页查询用户列表
     * @author 龘鵺
     * @datetime 2024-06-20 20:28:00
     * @version 1.0
     */
    @Override
    public R<?> findParamPageList(UserVo row) {
        SystemUserVo systemUserVo = getUser();
        row.setGtaeOperaterStatus(NumeralUtil.POSITIVE_ONE);
        int count = userMapper.findPageListCount(row);
        if (count == NumeralUtil.POSITIVE_ZERO) {
            return R.ok();
        }
        List<UserVo> list = userMapper.findPageList(row);
        return R.ok(list, count);
    }
}